//
//  SegmentItemTitleView.swift
//  PageNavigator
//
//  Created by 张奇 on 2025/8/14.
//

import UIKit

class SegmentItemTitleCell: UICollectionViewCell, SegmentItemViewProtocol {
    private weak var label: UILabel!
    /// label的numberOfLines
    open var titleNumberOfLines: Int = 1
    /// title普通状态的textColor
    open var titleNormalColor: UIColor = .black
    /// title选中状态的textColor
    open var titleSelectedColor: UIColor = .red
    /// title普通状态时的字体
    open var titleNormalFont: UIFont = UIFont.systemFont(ofSize: 15)
    /// title选中时的字体
    open var titleSelectedFont: UIFont = UIFont.systemFont(ofSize: 15)
    open var title: String?

    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        initUI()
    }
    
    func initUI() {
        let label = UILabel.init(frame: bounds)
        self.addSubview(label)
        label.text = title
        label.font = titleNormalFont
        label.textColor = titleNormalColor
        self.label = label
    }
    
    func segmentItemContentSize() -> CGSize {
        guard let title = self.title else {
            return CGSize.zero
        }
        let size = NSString(string: title).boundingRect(with: CGSize(width: CGFloat.infinity, height: CGFloat.infinity), options: [.usesFontLeading, .usesLineFragmentOrigin], attributes: [NSAttributedString.Key.font : titleNormalFont], context: nil).size
       return size
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        self.label.frame = self.bounds
    }
    
    func segmentItemViewDisplay(associated obj: Any?) {
        
    }
    
    func segmentItemViewEndDisplay(associated obj: Any?) {
        
    }
    
    func refreshScrollingSegmentItem(context: SegmentScrollingTransitionContext, associated obj: Any?) {
        if context.currentIndex == context.from {
            // 转移出去
            label.text = title
            label.font = titleSelectedFont.interpolate(to: titleNormalFont, percent: context.percent)
            label.textColor = titleSelectedColor.interpolate(to: titleNormalColor, percent: context.percent)
        } else {
            //转入进来
            label.text = title
            label.font = titleNormalFont.interpolate(to: titleSelectedFont, percent: context.percent)
            label.textColor = titleNormalColor.interpolate(to: titleSelectedColor, percent: context.percent)
        }
    }
    
    func refreshSegmentItemView(context: SegmentSelectedTransitionContext, associated obj: Any?, state: UIControl.State) {
        if state == UIControlState.normal {
            // 常规状态
            label.text = title
            label.font = titleNormalFont
            label.textColor = titleNormalColor
        } else {
            label.text = title
            label.font = titleSelectedFont
            label.textColor = titleSelectedColor
        }
    }
}
